package iot.core.util;

import java.lang.reflect.InvocationTargetException;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamUtil {
    public static <T> T get(List<T> list, Predicate<? super T> predicate ){
        var op=list.stream().filter(predicate).findFirst();
        if(op.isPresent()){
            return  op.get();
        }
        return null;
    }
    public static <T> T getOrDefault(List<T> list, Predicate<? super T> predicate,Class<T> tClass ){
        var op=list.stream().filter(predicate).findFirst();
        if(op.isPresent()){
            return  op.get();
        }
        try {
            return tClass.getDeclaredConstructor().newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> list(List<T> list, Predicate<? super T> predicate ){
        var l=list.stream().filter(predicate).collect(Collectors.toList());
         return  l;
    }

    public static <T> List<T> list(List<T> list, Predicate<? super T> predicate,Comparator<? super T> comparator ){
        var l=list.stream().filter(predicate)
                 .sorted(comparator)
                .collect(Collectors.toList());
        return  l;
    }

}
